import Vue from 'vue';
import Router from 'vue-router';
import {routerConfig} from './RouterConfig';
import {store} from '@/store/Store';
import ViewUI from 'view-design';
import {settings} from '@/config/Settings';
import {userBloc} from '@/store/module/User';
import {authBloc} from '@/store/module/Auth';
import {handleRouteClosebtn} from '@/base/util/tools';

const {homeName} = settings;

Vue.use(Router);

export const router = new Router({
  routes: routerConfig,
  mode: 'history',
  base: 'admin'
});
const LOGIN_PAGE_NAME = 'login';

const turnTo = (to: any, access: any, next: any) => {
  next(); // 有权限，可访问
  // else next({replace: true, name: 'login'}) // 无权限，重定向到401页面
};

router.beforeEach((to, from, next) => {
  handleRouteClosebtn(to, from);
  // @ts-ignore
  ViewUI.LoadingBar.start();
  const token = store.state.auth.accessToken;
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME
    });
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next();
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName
    });
  } else {
    if (userBloc.state.userIdentity.id === 0) {
      userBloc.renew().then(res => {
        turnTo(to, store.state.user.userIdentity.roles, next);
      }).catch(e => {
        console.warn('GetAccountInfoActionAsync', e);
        authBloc.logout();
        next({
          name: LOGIN_PAGE_NAME
        });
      });
    } else {
      turnTo(to, store.state.user.userIdentity.roles, next);
    }
  }
});

router.afterEach(to => {
  // @ts-ignore
  ViewUI.LoadingBar.finish();
  window.scrollTo(0, 0);
});
